package org.dromara.system.util.lsqd;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * Aes 加密工具
 *
 * @author lizhixin
 * @date 2023-6-28 18:08:56
 */
@Slf4j
public class AesUtil {

    /**
     * 破解时密匙长度是规定了的
     * 如果密匙长度有问题会报错：Key length not 128/192/256 bits.
     * 意思就比如密匙长度不是16位 就会报错~
     * 所以需要填充密匙长度
     *
     * @param s
     * @param length
     * @return
     */
    private static byte[] getBytes(String s, int length) {
        int fixLength = length - s.getBytes().length;
        if (s.getBytes().length < length) {
            byte[] S_bytes = new byte[length];
            System.arraycopy(s.getBytes(), 0, S_bytes, 0, s.getBytes().length);
            for (int x = length - fixLength; x < length; x++) {
                S_bytes[x] = 0x00;
            }
            return S_bytes;
        }
        return s.getBytes();
    }


    /**
     * 加密
     *
     * @param content
     * @return
     */
    public static String encryptToBase64(String key, String content) {
        AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes(StandardCharsets.UTF_8));
        return aes.encryptBase64(content);
    }

    /**
     * 加密
     *
     * @param content
     * @return
     */
    public static String decryptFromBase64(String key, String content) {
        AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes(StandardCharsets.UTF_8));
        return aes.decryptStr(content);
    }
}
